<script setup>
import {ref} from "vue";
import {ElMessage} from "element-plus";
import {categoryAddAPI, categoryEditAPI} from "@/api/AdminApi/category.js";

const props = defineProps({
  dialogParams: Object
})

// 表单信息
const form = ref({
  id: null,
  name: null,
  buyTimes: null
})

// 开启对话框时的操作
const handleOpen = () => {
  if (props.dialogParams && props.dialogParams.category && props.dialogParams.category.id) {
    form.value = props.dialogParams.category
  }
}

// 关闭对话框时的操作
const handleClose = () => {
  formRef.value.resetFields()
}

const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 10, message: '名称长度在 2 到 10 个字符之间', trigger: 'blur' }
  ]
}

// 添加和编辑
const emit = defineEmits(['close'])
const formRef = ref()
const editCategory = async () => {
  await formRef.value.validate()
  const res = await categoryEditAPI(form.value)
  if (res.code === 1) {
    ElMessage.success("更新成功")
    emit('close')
  } else {
    ElMessage.error(res.msg)
  }
}

const addCategory = async () => {
  await formRef.value.validate()
  const res = await categoryAddAPI(form.value)
  if (res.code === 1) {
    ElMessage.success("添加成功")
    emit('close')
  } else {
    ElMessage.error(res.msg)
  }
}
</script>

<template>
  <el-dialog
      @open="handleOpen"
      @close="handleClose"
      :title="dialogParams.title"
      destroy-on-close
      width="500"
      align-center>
    <el-form ref="formRef" :rules="rules" :model="form">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item v-if="dialogParams.category != null" label="购买次数">
        <el-input v-model="form.buyTimes" disabled></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editCategory" v-if="dialogParams.category != null">修改</el-button>
      <el-button @click="addCategory" v-else>提交</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>
